#include <xp/bas/sio.h>
#include <xp/bas/stdio.h>
#include <xp/bas/locale.h>
#include <xp/bas/string.h>
#include <xp/bas/errno.h>

#ifdef __linux
#include <mcheck.h>
#endif

void load_and_show (xp_vstr_t* vec, const xp_char_t* file);

int xp_main (int argc, xp_char_t* argv[])
{
	xp_vstr_t vec;
	int i;
	
#ifdef __linux
	mtrace ();
#endif

	if (argc != 2) {
		xp_printf (XP_TEXT("usage: %s source_file\n"), argv[0]);
		return -1;
	}

/*
	if (xp_setlocale () == -1) {
		xp_printf (XP_TEXT("cannot setlocale\n"));
		return -1;
	}
*/

	if (xp_vstr_open (&vec) == XP_NULL) {
		xp_printf (XP_TEXT("failed to open vstr\n"));
		return -1;
	}

	for (i = 0; i < 2; i++) {
		load_and_show (&vec, argv[1]);
		xp_printf (XP_TEXT("-----------------------\n\n"));
	}


	xp_vstr_close (&vec);
#ifdef __linux
	muntrace ();
#endif
	return 0;
}

void load_and_show (xp_vstr_t* vec, const xp_char_t* file)
{
	xp_sio_t src;
	xp_char_t buf[1000], ** p; 
	xp_size_t err = 0;


	if (xp_sio_open (&src, file, XP_TEXT("r")) == XP_NULL) {
		xp_printf (XP_TEXT("cannot sio_open [%s]\n"), file);
		return;
	}

	xp_vstr_clear (vec);

	for (;;) {
		xp_ssize_t n = xp_sio_gets (&src, buf, xp_countof(buf));
		if (n == 0) break;

		if (n == -1) {
			if (xp_errno != XP_EILSEQ) break;

			err++;
			if (err > 10) break;
			continue;
		}

		if (xp_vstr_append (vec, buf) == -1) {
			xp_printf (XP_TEXT("failed to add string: %s\n"), buf);
			break;
		}
	}

	if (err > 0) {
		xp_printf (XP_TEXT("=== %d sequence error(s) ===\n"), err);
	}

	xp_sio_close (&src);	

	for (p = vec->vector; *p != XP_NULL; p++) {
		xp_printf (XP_TEXT("%s"), *p);
	}
}

